package 力扣日常刷题.木22二月.第20天226;

/**
 * @author 帅小伙
 * @date 2022/2/26
 * @description
 */
public class Demo155螺旋矩阵 {

    public static void main(String[] args) {
        int[][] matrix ={{1,2,3,4},{5,6,7,8},{9,10,11,12}};

        int[] ints = SpiralMatrix(matrix);

        for (int anInt : ints) {
            System.out.println(anInt+" ");
        }


    }

    public static int[] SpiralMatrix(int[][] matrix) {
        // write code here

        int n = matrix.length;
        if (n == 0) return new int[0];
        int m = matrix[0].length;
        if (m == 0) return new int[0];
        int[] ans = new int[n * m];
        boolean[][] isVisited = new boolean[n][m];
        int[] dx = {0, 1, 0, -1}, dy = {1, 0, -1, 0};
        int x = 0, y = 0, d = 0;
        for (int i = 0; i < n * m; i++) {
            if (x < 0 || x >= n || y < 0 || y >= m || isVisited[x][y]) {
                x -= dx[d%4];
                y -= dy[d%4];
                d++;
                x += dx[d%4];
                y += dy[d%4];
            }
            ans[i] = matrix[x][y];
            isVisited[x][y] = true;
            x += dx[d%4];
            y += dy[d%4];
        }
        return ans;
    }

}
